<template>
    <div>
        <div>
            <van-nav-bar title="编辑任务" @click-left="onClickLeft" left-arrow />
        </div>
        <div style="width: 95vw; margin: 10px auto;">
            <card ref="cardref" :Objapi="Objapi" :formData="form"  :cardList="cardList" @cardItem="getItem" @formChange="onChildFormChange"></card>
        </div>
    </div>
</template>

<script>
import card from './components/card.vue';
import {formatDT} from '@/utils/utils'
import backMixin from '../../mixins/backMixin'

export default {
    mixins: [backMixin],
    components: {
        card,
    },
    data() {
        return {
            Objapi: this.$api.getlistUpdate,
            cardList: [
                {
                    name: '责任人',
                    value: 'owner',
                    key: 'zrr',
                    icon: 'arrow'
                }, {
                    name: '任务开始时间',
                    value: 'beginDate',
                    key: 'rwkssj',
                    icon: 'notes-o'
                }, {
                    name: '任务结束时间',
                    value: 'endDate',
                    key: 'rwjssj',
                    icon: 'notes-o'
                }
            ],
            listTree: [],
            selData: [],
            form: {},
            deptMemberTree: [], //责任人
        }
    },
    computed: {
        // 从 Vuex 获取选择回传的数据与资产信息
        selectedData() {
            return this.$store.state.assectData.selectPersonnel || []
        },
        assectInfo() {
            return this.$store.state.assectData.assectInfo || {}
        },
    },
    watch: {
        assectInfo: {
            // 当 Vuex 中的资产信息发生变化时，同步到本地表单并回填 UI
            handler(newValue) {
                if (!newValue) return
                console.log('assectInfo changed:', newValue)
                this.updateFormData(newValue)
            },
            deep: true,
            immediate: true
        },
        selectedData: {
            // 监听从选择页返回的数据（人员/组织等），并写回到本地表单
            handler(newValue) {
                if (!Array.isArray(newValue) || newValue.length === 0) return
                console.log('selectedData changed:', newValue)

                const ids = []
                const names = []
                newValue.forEach(e => {
                    if (!e) return
                    const id = e.id ?? e.memberId ?? e.orgId
                    const text = e.text ?? e.memberName ?? e.orgName
                    if (id !== undefined && id !== null && id !== '') ids.push(id)
                    if (text) names.push(text)
                })

                this.form.ownerId = ids.join(',')
                this.form.owner = names.join(',')

                this.$nextTick(() => {
                    this.updateCardForm()
                })
            },
            deep: true
        }
    },
    mounted() {
        console.log('editTask mounted')
        this.setformdata()
        // 处理从选择页返回的数据（如果有）
        this.handleBackDataFromRoute()
        this.getdeptMemberTree()
    },
    activated() {
        // 当页面被 keep-alive 激活时也处理返回数据
        console.log('editTask activated')
        this.handleBackDataFromRoute()
    },
    methods: {
        // 统一的表单更新方法
        updateFormData(data) {
            this.form = Object.assign({}, data)
            // 格式化日期
            if (this.form.beginDate) {
                this.form.beginDate = formatDT(this.form.beginDate, 'yyyy-MM-dd')
            }
            if (this.form.endDate) {
                this.form.endDate = formatDT(this.form.endDate, 'yyyy-MM-dd')
            }
            this.updateCardForm()
        },
        
        // 统一更新card组件表单的方法
        updateCardForm() {
            this.$nextTick(() => {
                if (this.$refs.cardref && typeof this.$refs.cardref.setformdata === 'function') {
                    console.log('Calling cardref.setformdata with:', this.form)
                    this.$refs.cardref.setformdata(this.form)
                } else {
                    console.warn('cardref not found or setformdata method not available')
                }
            })
        },
        
        setformdata() {
            // 初始化本地表单，来源于 Vuex 中的资产信息
            console.log('setformdata called')
            if (this.$route.name === 'editTask') {
                const d = this.$store.state.assectData.assectInfo || {}
                this.updateFormData(d)
            }
        },
        
        getdeptMemberTree(){
            this.$Geting(this.$api.getdeptMemberTree, {}).then(res => {
                if (res.code === '0' && res.data) {
                    this.deptMemberTree = res.data
                    this.$store.commit('assectData/setdeptMemberTree', this.deptMemberTree)
                }
            })
        },
        
        getItem(v) {
            if (v.key == 'zrr') {
                // 跳转时携带返回路由名称，选择完成后将用 query.backData 返回
                this.$router.push({ name: 'assectType', params: { key: 'zrr' }, query: { returnName: 'editTask' } })
            }
        },
        
        // 解析返回数据（优先从 Vuex 读取，兼容路由 query.backData）
        handleBackDataFromRoute() {
            let backData = null
            try {
                backData = this.$store && this.$store.state && this.$store.state.assectData && this.$store.state.assectData.returnData
                if (backData != null) {
                    try { 
                        this.$store.commit('assectData/setReturnData', null) 
                    } catch (e) { 
                        console.log('Clear returnData failed:', e)
                    }
                }
            } catch (err) {
                backData = null
            }
            if (backData == null) backData = this.$route.query.backData
            if (!backData) {
                console.log('No backData found')
                return
            }
            
            console.log('handleBackDataFromRoute with:', backData)
            
            let parsed = null
            try {
                parsed = typeof backData === 'string' ? JSON.parse(backData) : backData
            } catch (e) {
                parsed = backData
            }

            // 支持数组（多选）或对象/单项
            let personnelList = []
            if (Array.isArray(parsed)) {
                personnelList = parsed.map(item => {
                    if (!item) return null
                    const id = item.memberId ?? item.id ?? item.value ?? ''
                    const text = item.memberName ?? item.text ?? item.name ?? ''
                    return id !== undefined && id !== null ? { id, text } : null
                }).filter(Boolean)
            } else if (parsed && typeof parsed === 'object') {
                const id = parsed.memberId ?? parsed.id ?? parsed.value ?? ''
                const text = parsed.memberName ?? parsed.text ?? parsed.name ?? ''
                if (id !== '' || text !== '') personnelList = [{ id, text }]
            }

            if (personnelList.length) {
                const normalized = personnelList.map(p => ({ id: p.id, text: p.text }))

                // 直接回填到本页表单（不再依赖 Vuex）
                const idArr = normalized.map(i => i.id).filter(i => i !== undefined && i !== null)
                const nameArr = normalized.map(i => i.text).filter(Boolean)
                this.form.ownerId = idArr.join(',')
                this.form.owner = nameArr.join(',')
                
                this.updateCardForm()
            }

            try {
                this.$router.replace({ query: {} })
            } catch (e) {
                console.log('Clear query failed:', e)
            }
        },
        
        onClickLeft() {
            // 使用 mixin 的 navigateBack 以支持 query 中的 backTo JSON 返回
            this.navigateBack()
            this.form = {}
        },
        
        // 接收子组件回填的单字段更新并同步到本页 form
        onChildFormChange(payload) {
            if (!payload || !payload.key) return
            console.log('onChildFormChange:', payload)
            
            // 采用响应式更新 parent's form
            this.$set(this.form, payload.key, payload.value)
            
            // 同步回 card 组件（可选，确保两端一致）
            this.$nextTick(() => {
                this.updateCardForm()
            })
        }
    },
    
    beforeDestroy(){
        this.form = {}
    },
}
</script>

<style scoped></style>